
import { Globle } from "../Utils/Globle";

export class HttpUtil {

    public static get(url: string, params: { [x: string]: string | number | boolean; }, callback: (start: boolean, date: any) => void) {
        let dataStr = '';
        Object.keys(params).forEach(key => {
            dataStr += key + '=' + encodeURIComponent(params[key]) + '&';
        })
        if (dataStr !== '') {
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
            url = url + '?' + dataStr;
        }
        url = Globle.apiURL + url;
        let xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                let response = xhr.responseText;
                if (xhr.status >= 200 && xhr.status < 300) {
                    let data = JSON.parse(response);
                    callback(true, data);
                } else {
                    callback(false, response);
                }
            }
        };
        xhr.send();
    }

    //Post请求
    public static post(url: string, param:any, callback: (start: boolean, date: any) => void,type:number = 0) {
        url =  Globle.apiURL+ url;
        var xhr = new XMLHttpRequest();
        let dataStr = '';
        Object.keys(param).forEach(key => {
            dataStr += key + '=' + encodeURIComponent(param[key]) + '&';
        })
        if (dataStr !== '') {
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
        }
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.setRequestHeader('X-APP-Key', '8d0c438b-783b-47f5-a546-fe5700dbdeb2')
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                let response = xhr.responseText;
                if (xhr.status >= 200 && xhr.status < 300) {
                    let data = JSON.parse(response);
                    if(typeof(data.d) == "string"){
                    }
                    if(data.e){
                    }
                    callback(true, data);
                } else {
                    callback(false, response);
                }
            }else{
                if(!navigator.onLine){
                }
            }
        };
        xhr.send(param);
    }
}